class SavePaySDK{constructor(t,e,o){this.config=t,this.checkoutAttributes=e,this.options=o,this.renderOptions=null,this.forceAjaxMode=!1,this.paymentMethodOptionsObserver=null,this.logger=this.logger.bind(this),this.cartForms=[],this.checkoutButtons=[],this.discountRemoved=!1,this.discountApplied=!1,this.initialize()}logger(t,e,o=null){"true"==this.options.debug&&"error"==t&&console.error("[❌ savepay] "+e,o),"true"==this.options.debug&&"warn"==t&&console.warn("[⚠️ savepay] "+e,o),"true"==this.options.debug&&"info"==t&&console.info("[ℹ️ savepay] "+e,o),"true"==this.options.debug&&"success"==t&&console.info("[✅ savepay] "+e,o),"true"==this.options.debug&&"search"==t&&console.info("[🔍 savepay] "+e,o)}initialize(){console.group("[🤑 savepay] b240728 - Julho/24 (Estável) loading..."),console.group("load configs"),console.log("configs loaded",this.config),console.log("checkout attributes loaded",this.checkoutAttributes),this.config&&"true"!=this.config.discountEnabled?console.log("⚠️ discount configuration is not enabled. To show the discount, please activate it on app config"):console.log("✅ discount configuration enabled. :)"),this.options&&"true"==this.options.debug&&console.log("🛠️ debug mode is enabled. To disable it, please deactivate it on app config"),console.groupEnd(),console.groupEnd()}render(t){this.logger("info","render with options "+JSON.stringify(t)),t&&"ajax"==t.applyMode?this.logger("info","apply mode is ajax. No hidden fields will be created on cart form."):this.logger("info","apply mode is default. Hidden fields will be created on cart form."),this.renderOptions=t,this.renderCartDiscountTrigger(t)}async discountAppliedOnAjaxCart(){this.config&&"true"==this.config.discountEnabled&&fetch(window.Shopify.routes.root+"cart.js").then(t=>t.json()).then(t=>"yes"==t?.attributes?.paymentDiscountCheck)}async applyDiscountOnAjaxCart(){var t;this.config&&"true"==this.config.discountEnabled&&(this.logger("info","applying discount on ajax cart"),(t=new FormData).append("attributes[paymentDiscountCheck]","yes"),fetch(window.Shopify.routes.root+"cart/update.js",{method:"POST",body:t}).then(t=>t.json()).then(t=>{this.logger("success","discount applied on cart.",JSON.stringify(t))}))}async removeDiscountFromAjaxCart(){var t;this.config&&"true"==this.config.discountEnabled&&(this.logger("info","removing discount from ajax cart"),(t=new FormData).append("attributes[paymentDiscountCheck]","no"),fetch(window.Shopify.routes.root+"cart/update.js",{method:"POST",body:t}).then(t=>t.json()).then(t=>{this.logger("success","discount removed from cart.",JSON.stringify(t))}))}getCartForms(){let e=[];return e=(e=(e=(e=e.concat(Array.from(document.querySelectorAll('form[action="/cart"]')))).concat(Array.from(document.querySelectorAll('form[action="/checkout"]')))).concat(Array.from(document.querySelectorAll("form.cart")))).concat(Array.from(document.querySelectorAll("form#cart"))),this.renderOptions?.cartFormSelector&&""!=this.renderOptions.cartFormSelector&&this.renderOptions.cartFormSelector.split("
").forEach(t=>{e=e.concat(Array.from(document.querySelectorAll(t)))}),e&&0!=e.length?this.logger("success",e.length+" cart forms was found.",e):(this.logger("error","cart form was not found. This is necessary to discount works."),this.logger("warn","forcing ajax mode to try apply discount."),this.forceAjaxMode=!0),e}buildPaymentDiscountHiddenElement(t,e){var o=document.createElement("input");return o.setAttribute("type","text"),o.setAttribute("id",`savepay-${e}-${t.id}-cart__cart_attributes_paymentDiscountCheck`),o.setAttribute("name","attributes[paymentDiscountCheck]"),o.setAttribute("style","display: none"),o.value="no","yes"==this.checkoutAttributes.paymentDiscountCheck&&(o.value="yes"),o}injectPaymentDiscountHiddenElement(t,e){t.querySelector("#"+e.id)||(this.logger("info",`[🔄 savepay] paymentDiscountHiddenElement #${e.id} not created. Creating...`),t.append(e),t=t.querySelector("#"+e.id),this.logger("info",`[🔄 savepay] paymentDiscountHiddenElement #${e.id} created? `+(t?"yes":"no")))}renderFormFields(){if(this.config&&"true"==this.config.discountEnabled){var t=this.getCartForms();this.cartForms=t;let o=0;t.forEach(t=>{this.logger("seach",`cart form ${o} found.`,t),this.logger("info","creating paymentDiscountCheck hidden input on form "+t.id);var e=this.buildPaymentDiscountHiddenElement(t,o);this.injectPaymentDiscountHiddenElement(t,e),o++})}}getCheckoutButtons(){let o=[];return this.renderOptions?.checkoutButton?.description&&""!=this.renderOptions.checkoutButton.description&&this.renderOptions.checkoutButton.description.split("
").forEach(e=>{var t;e&&""!=e&&(this.logger("search","searching for checkoutButton with description "+e),o=o.concat(Array.from(document.querySelectorAll(`input[value="${e}" i]`))),t=Array.from(document.querySelectorAll("a,button")).filter(function(t){return t?.innerText?.toLowerCase().includes(e.toLowerCase())||t?.innerHTML.toLowerCase().includes(e.toLowerCase())}),this.logger("search",t.length+" elements found with description "+e),o=o.concat(t))}),0==o.length?this.logger("error","checkoutButton instances was not found."):this.logger("success",o.length+" checkoutButton instances was found.",o),new Set(o)}buildDiscountButtonElement(t){let e=null;var o;return this.renderOptions.buttonHTML&&""!=this.renderOptions.buttonHTML?(o=new DOMParser,e=o.parseFromString(this.renderOptions.buttonHTML,"text/html").body.firstChild,this.logger("info","created checkout button from HTML",e)):(e=t.cloneNode(!0),this.logger("info","clonned checkout button",e),this.renderOptions.buttonCSS&&""!=this.renderOptions.buttonCSS&&(e.style=this.renderOptions.buttonCSS,this.logger("info","applied css on checkout button",e)),"submit"==t?.type&&"input"==t?.tagName?(this.logger("search",`checkoutButton ${t.id} is input type submit`),this.renderOptions.buttonDescription?e.value=this.renderOptions.buttonDescription.replace("_paymentGatewayName_",this.config.paymentGatewayName).replace("_discountPercentage_",this.config.discountPercentage):e.value=`Finalizar com ${this.config.paymentGatewayName} (${this.config.discountPercentage}% de desconto)`):(this.logger("search",`checkoutButton ${t.id} is button type`),this.renderOptions.buttonDescription?e.innerText=this.renderOptions.buttonDescription.replace("_paymentGatewayName_",this.config.paymentGatewayName).replace("_discountPercentage_",this.config.discountPercentage):e.innerText=`Finalizar com ${this.config.paymentGatewayName} (${this.config.discountPercentage}% de desconto)`)),e.setAttribute("id","savepay-button-"+t.id),e}checkSavePayButtonInjected(t){this.logger("search","checking if discountButtonElement was already injected before or after checkoutButton "+t.id);var e=t.nextElementSibling;return e&&e.id==="savepay-button-"+t.id?(this.logger("info","discountButtonElement already injected after checkoutButton "+t.id),!0):(e=t.previousElementSibling)&&e.id==="savepay-button-"+t.id?(this.logger("info","discountButtonElement already injected before checkoutButton "+t.id),!0):(this.logger("info","discountButtonElement not injected before or after checkoutButton "+t.id),!1)}injectDiscountButtonElement(t,e){this.checkSavePayButtonInjected(t),this.checkSavePayButtonInjected(t)||(this.logger("info",`[🔄 savepay] discountButtonElement #${e.id} not created. Creating...`),this.renderOptions.wrapper?(this.logger("info","wrapper element found. Inserting discount button on "+this.renderOptions.wrapper),document.querySelector(this.renderOptions.wrapper).append(e)):("before"==this.renderOptions.buttonInsertPosition?(this.logger("info","inserting discount button before checkout button"),t.before(e)):(this.logger("info","inserting discount button after checkout button"),t.after(e)),t.parentElement.style.display="block"),t=document.querySelector("#savepay-button-"+t.id),this.logger("info",`[🔄 savepay] discountButtonElement #${e.id} created? `+(t?"yes":"no")))}async removeDiscountCallback(t){var e;this.discountRemoved?this.logger("info","discount already removed."):(this.discountRemoved=!0,"ajax"==this.renderOptions.applyMode||this.forceAjaxMode?(this.logger("info","removing discount on ajax cart"),await this.removeDiscountFromAjaxCart()):(this.logger("info","removing discount on cart form"),(e=document.querySelectorAll('input[name="attributes[paymentDiscountCheck]"]')).forEach(t=>{t.value="no"}),this.logger("success",`discount removed on ${e.length} elements.`)))}attachRemoveDiscountEvent(t){this.logger("info","attaching remove discount event to checkoutButton",t),t.addEventListener("click",this.removeDiscountCallback.bind(this))}async applyDiscountCallback(t){var e;this.discountApplied?this.logger("info","discount already applied."):(this.discountApplied=!0,"ajax"==this.renderOptions.applyMode||this.forceAjaxMode?(this.logger("info","applying discount on ajax cart"),await this.applyDiscountOnAjaxCart()):(this.logger("info","applying discount on cart form"),(e=document.querySelectorAll('input[name="attributes[paymentDiscountCheck]"]')).forEach(t=>{t.value="yes"}),this.logger("success",`discount added on ${e.length} elements.`)))}attachApplyDiscountEvent(t){this.logger("info","attaching apply discount event to discountButtonElements with id "+t.id),document.querySelectorAll("#"+t.id).forEach(t=>t.addEventListener("click",this.applyDiscountCallback.bind(this)))}renderCheckoutButtons(){var t=this.getCheckoutButtons();(this.checkoutButtons=t).forEach(t=>{this.logger("search",`checkoutButton ${t.id} found.`,t);var e=this.buildDiscountButtonElement(t);this.injectDiscountButtonElement(t,e),this.attachRemoveDiscountEvent(t),this.attachApplyDiscountEvent(e)})}renderCartDiscountTrigger(){this.config&&"true"==this.config.discountEnabled&&(this.renderFormFields(),this.renderCheckoutButtons())}bodyObserver(){new MutationObserver(t=>{t.forEach(t=>{(t.addedNodes||t.removedNodes)&&(this.renderFormFields(),this.renderCheckoutButtons())})}).observe(document.body,{childList:!0,subtree:!0})}}